import 'dart:io';

import 'package:flutter/material.dart';

class WifiService extends StatefulWidget {
  @override
  _WifiServiceState createState() => _WifiServiceState();
}

class _WifiServiceState extends State<WifiService> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    startServer();
  }

  Future<void> startServer() async {
    // 监听一个局域网内的IP地址和端口
    var server = await ServerSocket.bind('192.168.2.230', 3001);
    print('Server listening on ${server.address.address}:${server.port}');

    await for (var client in server) {
      handleConnection(client);
    }
  }

  void handleConnection(Socket client) {
    print('Connection from'
        ' ${client.remoteAddress.address}:${client.remotePort}');
    // 向客户端发送欢迎消息
    client.write('Welcome!\n');
    // 监听来自客户端的数据
    client.listen(
      (data) {
        print("客户端发来的消息：${String.fromCharCodes(data)}");
      },
      onDone: () {
        print('Client left');
        client.close();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WiFi链接设备传输'),
      ),
      body: Center(
          child: Column(
        children: [
          ElevatedButton(
            onPressed: () {},
            child: Text("通过WiFi 通讯"),
          )
        ],
      )),
    );
  }
}
